package test.multiple_task;


import beautiful.butterfly.distributed_task_processing_engine.api.MultipleTaskDataItemCollectorAndExecuterAndExecuter;
import beautiful.butterfly.distributed_task_processing_engine.task_manage.task_data_items_processor.task_data_item_data_manager.TaskItemStringAndParameterString;
import beautiful.butterfly.distributed_task_processing_engine.tools.TaskItemParameterStrings;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Slf4j
public class DBMultipleTask implements MultipleTaskDataItemCollectorAndExecuterAndExecuter<Long>
{

    @Override
    public List<Long> getTaskDataItemList(String taskParameter, int fetchTaskDataItemNum, int taskItemNum, List<TaskItemStringAndParameterString> taskItemStringAndParameterStringList) throws Exception
    {

        List<Long> list = new ArrayList<Long>();
        if (taskItemStringAndParameterStringList.size() == 0)
        {
            return list;
        }
        String all = null;
        for (int i = 0; i < taskItemStringAndParameterStringList.size(); i++)
        {
            Map<String, String> map = TaskItemParameterStrings.parseTaskItemParameterString(taskItemStringAndParameterStringList.get(i).getParameterString());
            all = map.get("all");
            break;//只取第一个
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < taskItemStringAndParameterStringList.size(); i++)
        {
            if (i > 0)
            {
                sb.append(",");
            }
            Map<String, String> map = TaskItemParameterStrings.parseTaskItemParameterString(taskItemStringAndParameterStringList.get(i).getParameterString());
            sb.append(map.get("mod"));
        }

        Connection connection = null;
        try
        {
            connection = getConnection();
            String sql = "select id from schedule_test where   mod(id," + all + ") in (" + sb.toString() + ") and sts ='N' limit " + fetchTaskDataItemNum;
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next())
            {
                list.add(resultSet.getLong("id"));
            }
            resultSet.close();
            preparedStatement.close();
            return list;
        } catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        } finally
        {
            if (connection != null)
            {
                connection.close();
            }

        }
    }


    public boolean dealWith(Long[] tasks) throws Exception
    {
        Connection connection = null;
        long id = 0;
        try
        {
            connection = getConnection();
            connection.setAutoCommit(false);
            for (int index = 0; index < tasks.length; index++)
            {
                id = ((Long) tasks[index]).longValue();
                log.debug("处理任务：" + id + " 成功！");
                String sql = "update schedule_test set sts ='y' ,deal_count = deal_count + 1 where id = ? and sts ='n' ";
                PreparedStatement statement = connection.prepareStatement(sql);
                statement.setLong(1, id);
                statement.executeUpdate();
                statement.close();
            }
            connection.commit();
        } catch (Exception e)
        {
            log.error("执行任务：" + id + "失败：" + e.getMessage(), e);
            if (connection != null)
            {
                connection.rollback();
            }
            return false;
        } finally
        {
            if (connection != null)
            {
                connection.close();
            }
        }
        System.out.println("处理任务：" + tasks.length);
        return true;
    }

    public Comparator<Long> getComparator()
    {
        return new Comparator<Long>()
        {
            public int compare(Long o1, Long o2)
            {
                return o1.compareTo(o2);
            }

            public boolean equals(Object obj)
            {
                return this == obj;
            }
        };
    }

    //
    public Connection getConnection() throws Exception
    {

        String URL = "jdbc:mysql://127.0.0.1:3306/dtpe?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
        String USER = "root";
        String PASSWORD = "root";
        //1.加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");
        //2.获得数据库链接
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }


}